#include "CogBase.h"

// ------------------------------------------------------------------------------------------

string toLower(const string& label)
{
	string lowercase;
	lowercase.reserve(label.size());
	for (size_t i = 0; i < label.size(); i++)
	{
		lowercase.push_back(tolower(label[i]));
	}
	return lowercase;
}

// ------------------------------------------------------------------------------------------

CogStopWatch::CogStopWatch()
: start(0),
  stop(0)
{
}

void CogStopWatch::startTimer() 
{
    start = clock();
}

void CogStopWatch::stopTimer() 
{
    stop = clock();
}

double CogStopWatch::getElapsedTime() 
{
    uint64_t time = stop - start;
    return ((double)time / CLOCKS_PER_SEC) ;
}

// ------------------------------------------------------------------------------------------

CogMessageLog globalMessageLog;

// -----

void CogMessageLog::show(ostream &out, CogMessageType type, CogMessageVerbosity minShowImport)
{
	boost::mutex::scoped_lock scoped_lock(messageMutex);
	list<CogMessage>::iterator message_iter = messageList.begin();
	while (message_iter != messageList.end())
	{
		if ((message_iter->type & type) && (message_iter->verbosity >= minShowImport))
		{
			out << message_iter->text << endl;
		}
		++message_iter;
	}
}

void CogMessageLog::dump(ostream &out, CogMessageType type)
{
	boost::mutex::scoped_lock scoped_lock(messageMutex);
	list<CogMessage>::iterator message_iter = messageList.begin();
	while (message_iter != messageList.end())
	{
		if (message_iter->type & type)
		{
			//out << "(" << message_iter->time << ") " << message_iter->text << endl;
			if (message_iter->verbosity <= minVerbose)
			{
				out << message_iter->text << endl;
			}
			message_iter = messageList.erase(message_iter);
		}
		else
		{
			++message_iter;
		}
	}
}

size_t CogMessageLog::length(CogMessageType type)
{
	size_t count = 0;
	boost::mutex::scoped_lock scoped_lock(messageMutex);
	list<CogMessage>::iterator message_iter = messageList.begin();
	for (; message_iter != messageList.end(); ++message_iter)
	{
		if (message_iter->type & type)
		{
			count++;
		}
	}
	return count;
}

void CogMessageLog::clear()
{
	boost::mutex::scoped_lock scoped_lock(messageMutex);
	messageList.clear();
}

void CogMessageLog::clear(CogMessageType type)
{
	boost::mutex::scoped_lock scoped_lock(messageMutex);
	list<CogMessage>::iterator message_iter = messageList.begin();
	while (message_iter != messageList.end())
	{
		if (message_iter->type & type)
		{
			message_iter = messageList.erase(message_iter);
		}
		else
		{
			++message_iter;
		}
	}
}

// ------------------------------------------------------------------------------------------